package com.example.mymvvmdemo.models.set_password;

import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CompoundButton;

import androidx.lifecycle.ViewModelProvider;

import com.example.mymvvmdemo.R;
import com.example.mymvvmdemo.base.BaseLoadActivity;
import com.example.mymvvmdemo.constants.Constants;
import com.example.mymvvmdemo.constants.UrlConstants;
import com.example.mymvvmdemo.constants.UrlTypeConstants;
import com.example.mymvvmdemo.databinding.ActivitySetPasswordBinding;
import com.example.mymvvmdemo.dialog.LoadingAnimDialog;
import com.example.mymvvmdemo.entity.FailEntity;
import com.example.mymvvmdemo.net.presenter.PostBodyPresenter;
import com.example.mymvvmdemo.net.view.IView;
import com.example.mymvvmdemo.utils.LogUtils;
import com.example.mymvvmdemo.utils.StrUtils;
import com.example.mymvvmdemo.utils.ToastUtils;

import java.util.HashMap;

public class SetPasswordActivity extends BaseLoadActivity<ActivitySetPasswordBinding> implements View.OnClickListener, IView.PostBodyView {

    public static void startSetPasswordActivity(Activity activity, String type, String account, String smsCode) {
        Intent intent = new Intent(activity, SetPasswordActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("account", account);
        intent.putExtra("smsCode", smsCode);
        activity.startActivity(intent);
    }

    private SetPasswordViewModel viewModel;
    private PostBodyPresenter postBodyPresenter;

    /*** 加载时候的Dialog */
    private LoadingAnimDialog loadingDialog;

    @Override
    protected void showDialog() {
        if (loadingDialog == null)
            loadingDialog = new LoadingAnimDialog(this, getResources().getString(R.string.load));
        if (!loadingDialog.isShowing()) loadingDialog.show(this);
    }

    @Override
    protected void dismissDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.close(this);
        }
    }

    @Override
    protected void initData() {
        viewModel = new ViewModelProvider(this).get(SetPasswordViewModel.class);
        postBodyPresenter = new PostBodyPresenter(this);
        viewModel.type = getIntent().getStringExtra("type");
        viewModel.account = getIntent().getStringExtra("account");
        viewModel.smsCode = getIntent().getStringExtra("smsCode");

    }

    @Override
    protected void initListener() {
        binding.include.ivBack.setOnClickListener(this);
        binding.tvNext.setOnClickListener(this);
        binding.ivClearPassword.setOnClickListener(this);
        binding.ivClearPasswordAgain.setOnClickListener(this);

        binding.cbPasswordAgain.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    binding.etPasswordAgain.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    binding.etPasswordAgain.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                }
                Selection.setSelection(binding.etPasswordAgain.getText(), binding.etPasswordAgain.getText().length());
            }
        });
        binding.etPasswordAgain.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                binding.ivClearPasswordAgain.setVisibility(charSequence.toString().length() > 0 ? View.VISIBLE : View.GONE);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        binding.cbPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    binding.etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    binding.etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                }
                Selection.setSelection(binding.etPassword.getText(), binding.etPassword.getText().length());
            }
        });
        binding.etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                binding.ivClearPassword.setVisibility(charSequence.toString().length() > 0 ? View.VISIBLE : View.GONE);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_next:
                setPassword();
                break;
            case R.id.iv_clear_password:
                binding.etPassword.setText("");
                break;
            case R.id.iv_clear_password_again:
                binding.etPasswordAgain.setText("");
                break;
            default:
                break;
        }
    }

    /**************************************自定义方法****************************************/
    private void setPassword() {

        String password = binding.etPassword.getText().toString();
        String passwordAgain = binding.etPasswordAgain.getText().toString();

        if (StrUtils.isEmpty(password)) {
            toast(R.string.input_password, ToastUtils.TOA_S);
            return;
        }
        if (StrUtils.isEmpty(passwordAgain)) {
            toast(R.string.input_password_again, ToastUtils.TOA_S);
            return;
        }
        if (!password.equals(passwordAgain)) {
            toast(R.string.input_password_different, ToastUtils.TOA_S);
            return;
        }

        if (viewModel.type.equals(Constants.REGISTER)) {
            startRegister(password, passwordAgain);
        } else if (viewModel.type.equals(Constants.FORGOT)) {
            startSetPassword(password, passwordAgain);
        }


    }

    private void startRegister(String password, String passwordAgain) {
        showDialog();
        HashMap<String, String> hashMap = new HashMap<>();
        if (viewModel.account.contains("@")) {
            hashMap.put("email", viewModel.account);
        } else {
            hashMap.put("mobile", viewModel.account);
        }
        hashMap.put("verify_code", viewModel.smsCode);
        hashMap.put("password", password);
        hashMap.put("password2", passwordAgain);
        LogUtils.d("verify_code:" + viewModel.smsCode);
        postBodyPresenter.startLoadPostBody(UrlConstants.registerUrl, hashMap, UrlTypeConstants.registerUrl);
    }

    private void startSetPassword(String password, String passwordAgain) {

        showDialog();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("account", viewModel.account);
        hashMap.put("verify_code", viewModel.smsCode);
        hashMap.put("new_password", password);
        hashMap.put("new_password2", passwordAgain);
        LogUtils.d("verify_code:" + viewModel.smsCode);
        postBodyPresenter.startLoadPostBody(UrlConstants.forgetPassword, hashMap, UrlTypeConstants.forgetPassword);

    }

    /*********************************数据请求回调************************************/
    @Override
    public void loadPostBodySuccess(String result, String type, int code) {
        if (type.equals(UrlTypeConstants.registerUrl)) {
            loadRegisterSuccess(result, code);
        } else if (type.equals(UrlTypeConstants.forgetPassword)) {
            loadForgetPasswordSuccess(result, code);
        }
    }

    @Override
    public void loadPostBodyFail(String message, String type) {
        if (type.equals(UrlTypeConstants.registerUrl)) {
            loadRegisterFail();
        } else if (type.equals(UrlTypeConstants.forgetPassword)) {
            loadForgetPasswordFail();
        }
    }

    @Override
    public void loadPostBodyAccountError(int code) {

    }

    @Override
    public void loadPostBodyNetWorkError(String type) {
        dismissDialog();
        toast(R.string.network_error, ToastUtils.TOA_W);
    }


    /*********************************处理请求后数据************************************/
    private void loadForgetPasswordSuccess(String result, int code) {
        dismissDialog();
        if (code != 200) {
//            FailEntity registerFailEntity = gson.fromJson(result, FailEntity.class);
//            String message = registerFailEntity.getData().getMessage().getMessages().get(0);
//            toast(message, ToastUtils.TOA_W);
            toast(R.string.send_code_fail, ToastUtils.TOA_W);
            return;
        }

        toast(R.string.forget_success, ToastUtils.TOA_S);
        viewModel.startLoginActivity(this);
        finish();
    }

    private void loadForgetPasswordFail() {
        dismissDialog();
        toast(R.string.app_error, ToastUtils.TOA_W);
    }

    private void loadRegisterSuccess(String result, int code) {
        dismissDialog();
        if (code != 200) {
            FailEntity registerFailEntity = gson.fromJson(result, FailEntity.class);
            String message = registerFailEntity.getData().getMessage().getMessages().get(0);
            toast(message, ToastUtils.TOA_W);
            return;
        }

        toast(R.string.register_success, ToastUtils.TOA_S);
        viewModel.startLoginActivity(this);
        finish();

    }

    private void loadRegisterFail() {
        dismissDialog();
        toast(R.string.app_error, ToastUtils.TOA_W);
    }

}